package com.slkj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.CountiesTaskDTO;
import com.slkj.dto.UserinfoDTO;
import com.slkj.entity.*;
import com.slkj.mapper.*;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CityService {
    @Autowired
    CityMapper cityMapper;
    @Autowired
    CityNodeMapper cityCompletsMapper;

    @Autowired
    CityAuditMapper cityDutyMapper;

    @Autowired
    FileMapper fileMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    HistoryService historyService;

    @Autowired
    TaskService taskService;

    public void insert(City city, String username) {

        //获取市直创建任务下的节点集合
        List<CityNode> cityNodes = city.getCityNodes();

        //多个市直任务单位集合
        List<String> units = city.getCityUntil();


        if (cityNodes == null || units == null) {
            throw new NullPointerException("空指针异常");
        }
        if (cityNodes.size() == 0 || units.size() == 0) {
            throw new NullPointerException("空指针异常");
        }
        List<Userinfo> userinfoList = userMapper.selectByUserIdList(units);
        if (userinfoList == null) {
            throw new NullPointerException("空指针异常");
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");

        for (CityNode cityNode : cityNodes) {
            List<String> projectTime = cityNode.getProjectTime();
            try {
                cityNode.setBeginTime(simpleDateFormat.parse(projectTime.get(0)));
                cityNode.setEndTime(simpleDateFormat.parse(projectTime.get(1)));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("日期格式转换异常");
            }
        }
        Userinfo userinfo = userMapper.selectByUsername(username);
        UserinfoDTO userinfoDTO = userService.getUserinfo(userinfo.getId());
        String type = userinfoDTO.getType();
        if (StringUtils.isBlank(type)) {
            throw new RuntimeException("任务发起人type为空");
        }
        city.setUsername(username);
        //创建市值任务
        cityMapper.insert(city);
        //循环市直任务下的节点
        for (CityNode cityNode : cityNodes) {
            //将市直任务得id赋给没给子节点得nid，方便关联
            cityNode.setCid(city.getId());
            //每次循环一个节点，添加到节点表中
            cityCompletsMapper.insert(cityNode);
            List<File> files = cityNode.getFileList();

            //循环查询单位
            for (Userinfo userinfoSelect : userinfoList) {
                CityAudit cityAudit = new CityAudit();
                //将单位名称添加到任务审核的单位名称
                cityAudit.setUtilName(userinfoSelect.getName());
                //将市值任务ID传过去
                cityAudit.setCid(city.getId());
                //将节点id传过去
                cityAudit.setNid(cityNode.getId());
                //审核状态为初始“未审核”
                cityAudit.setAudit("待上传");
                //灯初始为灰色
                cityAudit.setLight("灰灯");
                //开始时间
                cityAudit.setBeginTime(cityNode.getBeginTime());
                //结束时间
                cityAudit.setEndTime(cityNode.getEndTime());
                //任务标题
                cityAudit.setTitle(city.getTitle());
                //任务内容
                cityAudit.setContent(cityNode.getContent());
                //节点材料
                cityAudit.setMaterial(cityNode.getMaterial());
                //当前年度
                cityAudit.setYear(Calendar.getInstance().get(Calendar.YEAR));
                //任务发起人id
                cityAudit.setUserId(Integer.valueOf(userinfoSelect.getId()));
                cityDutyMapper.insert(cityAudit);

                if (files.size() != 0 & files != null) {
                    fileMapper.insert(files, "" + cityAudit.getId(), "4");
                }
                Map map = new HashMap();
                map.put("cityName", userinfoSelect.getUsername());
                runtimeService.startProcessInstanceByKey("City", cityAudit.getClass().getSimpleName().toLowerCase() + "/" + cityAudit.getId(), map);
                taskComplete(null, 1, cityAudit.getId() + "");
            }
        }

    }

    private void taskComplete(List<Map> mapList, int count, String dutyId) {
        CityAudit cityAudit = cityDutyMapper.selectByDutyId(dutyId);
        UserinfoDTO userinfo = userMapper.getUserinfoByUserId(cityAudit.getUserId() + "");
        String buniessKey = cityAudit.getClass().getSimpleName().toLowerCase() + "/" + cityAudit.getId();
        String buniessKeyLight = cityAudit.getClass().getSimpleName().toLowerCase() + "light/" + cityAudit.getId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKey).singleResult();
        ProcessInstance processInstanceLight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(buniessKeyLight).singleResult();
        ProcessInstance processInstanceTask = null;
        if (processInstance != null) {
            processInstanceTask = processInstance;
        } else if (processInstanceLight != null) {
            processInstanceTask = processInstanceLight;
        } else {
            throw new ActivitiException("找不到流程实例");
        }
        for (int i = 0; i < count; i++) {
            Task task = taskService.createTaskQuery().processInstanceId(processInstanceTask.getProcessInstanceId()).taskAssignee(userinfo.getUsername()).singleResult();
            if (mapList != null && mapList.size() != 0) {
                if (mapList.get(count - 1) != null) {
                    taskService.complete(task.getId(), mapList.get(count - 1));
                } else {
                    taskService.complete(task.getId());
                }
            } else {
                taskService.complete(task.getId());
            }
        }

    }


    //打分
    public void point(Integer point, List<String> idList) {
        for (String id : idList) {
            cityDutyMapper.point(point, id);
        }
    }

    //上传材料和追加材料
    public void taskUpload(List<File> fileList, String dutyId, List<Map> variables, String count) throws SQLException {
        CityAudit cityAudit = cityDutyMapper.selectByDutyId(dutyId);
        if (cityAudit == null) {
            throw new SQLException("找不到该任务");
        }
        if (!cityAudit.getAudit().equals("待上传") && !cityAudit.getAudit().equals("未通过待上传")) {
            throw new RuntimeException("不能上传文件");
        }
        fileMapper.insert(fileList, dutyId, "4");
        taskComplete(variables, Integer.parseInt(count), dutyId);
        String audit = "待审核";
        String light = "黄灯";
        cityDutyMapper.audit(audit, light, dutyId);
        cityDutyMapper.updateSubmitTime(new Date(), dutyId);
    }


    //通过
    public void audit(List<String> idList, List<Map> variables, String count) {

        for (String id : idList) {
            String cityDuty = cityDutyMapper.showAllAudit(id);
            if (cityDuty.equals("待审核")) {
                String light = "绿灯";
                taskComplete(variables, Integer.parseInt(count), id);
                cityDutyMapper.audit(variables.get(0).get("isPass") + "", light, id);
            } else if (cityDuty.equals("待上传") || cityDuty.equals("未通过待上传")) {
                throw new RuntimeException("该任务待上传材料");
            } else {
                throw new RuntimeException("该任务已结束");
            }
        }
    }

    //驳回
    public void worry(List<String> idList, List<Map> variables, String count) {
        for (String id : idList) {
            String cityDuty = cityDutyMapper.showAllAudit(id);
            System.out.println(cityDuty);
            if (cityDuty.equals("待审核")) {
                String light = "红灯";
                taskComplete(variables, Integer.parseInt(count), id);
                cityDutyMapper.worry(variables.get(0).get("isPass") + "", light, id);
            } else if (cityDuty.equals("待上传") || cityDuty.equals("未通过待上传")) {
                throw new RuntimeException("该任务待上传材料");
            } else {
                throw new RuntimeException("该任务已结束");
            }
        }

    }

    //亮灯调整以及原因
    public void why(String light, String why, List<String> idList, List<Map> variables) {
        for (String id : idList) {
            CityAudit cityAudit = cityDutyMapper.selectByDutyId(id);
            if (cityAudit == null) {
                throw new NullPointerException("空指针异常");
            } else {
                ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(cityAudit.getClass().getSimpleName().toLowerCase() + "/" + id).singleResult();
                ProcessInstance processInstancelight = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(cityAudit.getClass().getSimpleName().toLowerCase() + "light/" + id).singleResult();

                if (processInstance != null) {
                    runtimeService.deleteProcessInstance(processInstance.getProcessInstanceId(), "processInstance delete");
                }
                if (processInstancelight != null) {
                    runtimeService.deleteProcessInstance(processInstancelight.getProcessInstanceId(), "processInstance delete");
                }
                UserinfoDTO userinfo = userMapper.getUserinfoByUserId(cityAudit.getUserId() + "");


                variables.get(0).put("cityName", userinfo.getUsername());
                runtimeService.startProcessInstanceByKey("Citylight", cityAudit.getClass().getSimpleName().toLowerCase() + "light/" + id, variables.get(0));
                cityDutyMapper.why(variables.get(0).get("isPass") + "", light, why, id);
            }
        }

    }


    public PageInfo<CityAudit> shwoAll(String title, String userId, String light, Date beginDate, Date endDate, Integer page, Integer pageSize, String username, String status) {
        String utilName = "";
        if (StringUtils.isNotBlank(userId)) {
            UserinfoDTO userinfo = userMapper.getUserinfoByUserId(userId);
            utilName = userinfo.getName();
        }

        Userinfo selectByUsername = userMapper.selectByUsername(username);
        if (selectByUsername == null) {
            throw new NullPointerException("空指针异常");
        }
        String selectUserId = selectByUsername.getId();
        title = ("".equals(title) ? null : title);
        utilName = ("".equals(utilName) ? null : utilName);
        light = ("".equals(light) ? null : light);
        status = ("".equals(status) ? null : status);
        PageHelper.startPage(page, pageSize, true);
        List<CityAudit> cityAudits = cityDutyMapper.showAll(title, utilName, light, beginDate, endDate, username, selectUserId, status);
        PageInfo<CityAudit> pageInfo = new PageInfo(cityAudits);
        if (cityAudits != null && cityAudits.size() != 0) {
            List<File> fileList = fileMapper.selectByCityAudits(cityAudits, "4");
            if (fileList != null && fileList.size() != 0) {
                for (CityAudit cityAudit : cityAudits) {
                    boolean result = false;
                    List<File> countiesFileList = new ArrayList<>();
                    for (File file : fileList) {
                        if (cityAudit.getId().equals(file.getDutyId())) {
                            result = true;
                            countiesFileList.add(file);
                        }
                    }
                    if (result) {
                        cityAudit.setFileList(countiesFileList);
                    }
                }
            }
        }


        return pageInfo;

    }
}
